package com.yinhe.music.yhmusic.comment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.common.emoji.ExpressionGridFragment;
import com.yinhe.music.common.emoji.ExpressionShowFragment;
import com.yinhe.music.common.emoji.widget.ExpressionEditText;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.CommentListAdapter;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BasePresneterActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.utils.KeyboardUtil;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.utils.ViewUtils;
import com.yinhe.music.yhmusic.widget.CustomLoadMoreView;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class CommentListActivity extends BasePresneterActivity implements BaseQuickAdapter.OnItemChildClickListener,
        ExpressionGridFragment.ExpressionClickListener, ExpressionGridFragment.ExpressionDeleteClickListener,
        ICommentListContract.ICommentListView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edit_comment)
    ExpressionEditText editComment;
    @BindView(R.id.send)
    ImageView send;
    @BindView(R.id.emoji)
    ImageView emoji;
    @BindView(R.id.root_lyt)
    RelativeLayout rootLyt;
    @BindView(R.id.empty_text)
    TextView emptyText;
    @BindView(R.id.fl_emogi)
    FrameLayout fl_emogi;
    @BindView(R.id.loading_progress)
    ProgressBar progressBar;

    private int id;
    private String name;
    private String artist;
    private String coverUri;
    private CommentListAdapter commentAdapter;
    private boolean isEmogiShow;
    private ExpressionShowFragment expressionShowFragment;
    private int supportSoftInputHeight;
    private boolean keyboardShown;
    private static final int MAX_COMMENT_COUNT = 255;
    private int isLike;
    private int mPageNum;
    private String commentType;
    private CommentSection commentSection;
    private int position;

    CommentListPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_list);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            name        = getIntent().getStringExtra("name");
            coverUri    = getIntent().getStringExtra("cover");
            artist      = getIntent().getStringExtra("artist");
            id          = getIntent().getIntExtra("id", 0);
            commentType = getIntent().getStringExtra("commentType");
        }
        initView();
        setComment();
        initData(true);
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new CommentListPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    public void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        progressBar.setVisibility(View.GONE);
    }

    private void initData(boolean isRefresh) {
        if (isRefresh) {
            mPage = 1;
            mPageSize = 15;
        }

        mPresenter.getCommentList(mPage, mPageSize, commentType, id);
    }

    /**
     * 表情显示
     */
    private void replaceEmogi() {
        isEmogiShow = true;
        fl_emogi.setVisibility(View.VISIBLE);

        if (expressionShowFragment == null) {
            expressionShowFragment = ExpressionShowFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_emogi,
                    ExpressionShowFragment.newInstance()).commit();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setRootOnTouchListener() {
        rootLyt.setOnTouchListener((v, event) -> {
            KeyboardUtil.hideKeyboard(this);
            emoji.setImageResource(R.drawable.emoji_keyboard);
            return false;
        });
    }

    /**
     * 动态监听键盘状态
     */
    private void setListenerToRootView() {
        rootLyt.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                keyboardShown = KeyboardUtil.isKeyboardShown(rootLyt);
                if (fl_emogi != null) {
                    if (keyboardShown) {
                        emoji.setImageResource(R.drawable.ic_emoji);
                        if (isEmogiShow) {
                            isEmogiShow = false;
                            fl_emogi.setVisibility(View.GONE);
                        }
                        if (supportSoftInputHeight != ViewUtils.getSupportSoftInputHeight(CommentListActivity.this)) {
                            rootLyt.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            supportSoftInputHeight = ViewUtils.getSupportSoftInputHeight(CommentListActivity.this);
                            fl_emogi.getLayoutParams().height = supportSoftInputHeight;
                            fl_emogi.requestLayout();
                            rootLyt.getViewTreeObserver().addOnGlobalLayoutListener(this);
                        }
                    } else {
                        emoji.setImageResource(R.drawable.emoji_keyboard);
                        if (!isEmogiShow) {
                            fl_emogi.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
    }


    private void initView() {
        setToolbar("评论");
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        commentAdapter = new CommentListAdapter(null);
        setHeaderView();
        recyclerView.setAdapter(commentAdapter);
        commentAdapter.setLoadMoreView(new CustomLoadMoreView());
        commentAdapter.setOnLoadMoreListener(() -> {
            if (mPage <= mPageNum) {
                initData(false);
            } else {
                commentAdapter.loadMoreEnd();
            }
        }, recyclerView);
        commentAdapter.setPreLoadNumber(5);
        commentAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        commentAdapter.setOnItemChildClickListener(this);

        fl_emogi = findViewById(R.id.fl_emogi);
        setListenerToRootView();
        setRootOnTouchListener();
    }

    @OnClick(R.id.emoji)
    public void showEmoji() {
        if (isEmogiShow) {
            isEmogiShow = false;
            fl_emogi.setVisibility(View.GONE);
            KeyboardUtil.showKeyboard(this, editComment);
            emoji.setImageResource(R.drawable.ic_emoji);
        } else {
            int delay = 0;
            if (keyboardShown) {
                KeyboardUtil.hideKeyboard(this);
                emoji.setImageResource(R.drawable.emoji_keyboard);
                delay = 300;
            }
            mHandler.postDelayed(this::replaceEmogi, delay);
        }
    }

    private void setHeaderView() {
        View headView = getView(R.layout.comment_head_layout, recyclerView);
        TextView title = headView.findViewById(R.id.title);
        TextView typeName = headView.findViewById(R.id.type_name);
        TextView userName = headView.findViewById(R.id.user_name);
        ImageView cover = headView.findViewById(R.id.cover);
        GlideHelper.setImageResource(cover, coverUri, R.drawable.default_cover);
        typeName.setText(getNameByType(commentType));
        title.setText(name);
        userName.setText(artist);
        commentAdapter.addHeaderView(headView);
        fl_emogi = findViewById(R.id.fl_emogi);

        editComment.setFilters(new InputFilter[]{ inputFilter });
        setListenerToRootView();
        setRootOnTouchListener();
    }

    public String getNameByType(String type) {
        switch (type) {
            case IConstants.SONG:
                return "歌曲";
            case IConstants.MOVIE:
                return "视频";
            case IConstants.RADIO:
                return "电台";
            case IConstants.SONGMENU:
                return "歌单";
            case IConstants.ALBUM:
                return "专辑";
            case IConstants.RADIO_SONG:
                return "节目";
            default:
                return "";
        }
    }

    @Override
    public void onBackPressed() {
        if (isEmogiShow || KeyboardUtil.isKeyboardShown(rootLyt)) {
            fl_emogi.setVisibility(View.GONE);
            isEmogiShow = false;
            KeyboardUtil.hideKeyboard(this);
        } else {
            finish();
        }
    }

    private InputFilter inputFilter = new InputFilter() {
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                //Toast.makeText(MainActivity.this,"不支持输入表情", 0).show();
                //Toast.makeText(CommentListActivity.this,"不支持输入表情", Toast.LENGTH_SHORT);
                return "";
            }
            return null;
        }
    };

    private void setComment() {
        editComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String content = editComment.getText().toString();
                if (content.length() > 0) {
                    send.setImageResource(R.drawable.ic_send_clickable);
                    send.setClickable(true);
                } else {
                    send.setImageResource(R.drawable.ic_send_unclikable);
                    send.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        editComment.setOnFocusChangeListener((v, hasFocus) -> {
            MLog.info("fuck", "hasFocus " + hasFocus);
            if (hasFocus) {
                fl_emogi.setVisibility(View.GONE);
            }
        });

        editComment.setOnClickListener((v) -> {
            MLog.info("hzhenx", "editcomment didClick");
            if (isEmogiShow) {
                isEmogiShow = false;
                fl_emogi.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 发送评论
     */
    @OnClick(R.id.send)
    public void sendComment() {
        hideSoftKeyboard();
        if (!Preferences.getLoginSn().isEmpty()) {
            String content = editComment.getText().toString();
            if (!TextUtils.isEmpty(content) && content.length() < MAX_COMMENT_COUNT) {
                mPresenter.comment(id, content, commentType);
            } else {
                Toast.makeText(this, "请输入少于255个字", Toast.LENGTH_SHORT).show();
            }
        } else {
            startHome();
        }
    }

    @Override
    public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
        if (Preferences.getLoginSn().isEmpty()) {
            Toast.makeText(this, "重新登陆", Toast.LENGTH_SHORT).show();
            startLogin();
            return;
        }

        this.position = position;
        commentSection = (CommentSection) adapter.getData().get(position);
        isLike = commentSection.t.getCollectStatus();
        mPresenter.collect(commentSection.t.getCommentid(), IConstants.COMMENT, isLike);
    }

    /**
     * 这里必须实现表情点击后才能把具体表情传入edittext
     *
     * @param str
     */
    @Override
    public void expressionClick(String str) {
        ExpressionShowFragment.input(editComment, str);
    }

    @Override
    public void expressionDeleteClick(View v) {
        ExpressionShowFragment.delete(editComment);
    }

    @Override
    public void setCommentListUI(List<CommentSection> commentSectionList, int pageNum) {
        mPageNum = pageNum;
        setLoadMoreList(commentSectionList, mPageNum, commentAdapter);
    }

    @Override
    public void showEmptyUI(int visibility) {
        emptyText.setVisibility(visibility);
    }

    @Override
    public void setCommentUI() {
        UmengEventUtils.comment(this);
        KeyboardUtil.hideKeyboard(this);
        emoji.setImageResource(R.drawable.emoji_keyboard);
        if (isEmogiShow) {
            isEmogiShow = false;
            fl_emogi.setVisibility(View.GONE);
        }

        editComment.setText("");
        editComment.setHint("写下你的评论");
        initData(true);
    }

    @Override
    public void setLoadMoreFailUI() {
        commentAdapter.loadMoreFail();
    }

    @Override
    public void updateCollectUI() {
        if (isLike == 0) {
            int num = commentSection.t.getLikeNum() + 1;
            commentSection.t.setLikeNum(num);
            commentSection.t.setCollectStatus(1);
            commentAdapter.setData(position, commentSection);
        } else {
            int num = commentSection.t.getLikeNum() - 1;
            commentSection.t.setLikeNum(num > 0 ? num : 0);
            commentSection.t.setCollectStatus(0);
            commentAdapter.setData(position, commentSection);
        }
    }
}
